package com.example.administrator.testproject.downM3U8;

import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.daimajia.numberprogressbar.NumberProgressBar;
import com.example.administrator.testproject.R;
import com.example.administrator.testproject.download.DownState;
import com.example.administrator.testproject.download.listener.HttpDownOnNextListener;
import com.example.administrator.testproject.download.util.DBUtils;
import com.example.administrator.testproject.video.VideoActivity;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import rx.Observable;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
import rx.subjects.PublishSubject;

public class RxDownM3U8Activity extends AppCompatActivity implements View.OnClickListener {
    private String[] urls = {"http://1255417817.vod2.myqcloud.com/c7c63ce8vodgzp1255417817/b3e97ecf4564972819119068622/playlist.m3u8",
            "http://1255417817.vod2.myqcloud.com/c7c63ce8vodgzp1255417817/01c013b84564972819090978506/playlist.m3u8"};
    LiteDbM3U8DownUtil dbUtil;
    //临时下载目录
    private String tempDir = Environment.getExternalStorageDirectory().getPath() + File.separator + "m3u8temp";
    List<LiteM3U8DownInfo> listData;
    private NumberProgressBar progress;
    private TextView tvMsg;
    private HttpDownM3Manager manager;
    private List<LiteM3U8DownInfo> m3U8s;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rx_down_m3_u8);
        findViewById(R.id.btn_rx_down).setOnClickListener(this);
        findViewById(R.id.btn_rx_pause).setOnClickListener(this);
        findViewById(R.id.btn_rx_play).setOnClickListener(this);
        findViewById(R.id.btn_rx_delete).setOnClickListener(this);
        tvMsg = (TextView) findViewById(R.id.tv_msg);

        progress = (NumberProgressBar) findViewById(R.id.number_progress_bar);

        manager = HttpDownM3Manager.getInstance();
        dbUtil = LiteDbM3U8DownUtil.getInstance();
        listData = DBUtils.queryDownAll(LiteM3U8DownInfo.class);
        if (listData != null) {
            for (LiteM3U8DownInfo info : listData) {
                dbUtil.deleteDowninfo(info);
            }
        }
        m3U8s = new ArrayList<LiteM3U8DownInfo>();
        Observable.from(urls).map(new Func1<String, List<LiteM3U8DownInfo>>() {
            @Override
            public  List<LiteM3U8DownInfo> call(String url) {
                Log.e("Tag",Thread.currentThread().getName());
                LiteM3U8DownInfo m3U8 = M3MUtils.parseIndex(url, httpProgressOnNextListener);
                m3U8.setState(DownState.START);
                m3U8.setUrl(url);
                m3U8.setSavePath(m3U8.getBasepath());
                m3U8.setListener(httpProgressOnNextListener);
                m3U8s.add(m3U8);
                return m3U8s;
            }
        }).subscribeOn(Schedulers.io()).subscribe();

        PublishSubject<String> subject = PublishSubject.create();

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_rx_down:
                for (LiteM3U8DownInfo m3U8 : m3U8s) {
                    if (m3U8.getState() != DownState.FINISH) {
                        manager.startDown(m3U8);
                    }
                }
                break;
            case R.id.btn_rx_pause:
//                manager.pause(apkApi);
                break;
            case R.id.btn_rx_play:
                startActivity(new Intent(this, VideoActivity.class));
                break;
            case R.id.btn_rx_delete:
                M3MUtils.clearDir(new File(tempDir));
                break;
        }
    }

    boolean isLoad;
    /*下载回调*/
    HttpDownOnNextListener<ItemM3U8Ts> httpProgressOnNextListener = new HttpDownOnNextListener<ItemM3U8Ts>() {
        @Override
        public void onNext(ItemM3U8Ts baseDownEntity) {
            baseDownEntity.setState(DownState.FINISH);
//            tvMsg.setText("提示：下载完成");
            //更新进度条，m3u8记录下载过后的状态，防止ui阻塞
            long videoLengthForList = M3MUtils.getM3U8VideoLastLength(m3U8s);
            Log.e("Tag1", "下载中---" + videoLengthForList);
            progress.setMax(139565318/1000);
            progress.setProgress((int) (videoLengthForList/1000));
        }

        @Override
        public void onStart() {
//            tvMsg.setText("提示:开始下载");
        }

        @Override
        public void onComplete() {


            for (int i = 0; i < m3U8s.size(); i++) {
                DownState videoStatus = DownUtil.getVideoStatus(m3U8s.get(i).getTsList());
                if (videoStatus != DownState.FINISH) {
                    break;
                }
                isLoad = true;
            }
            if (isLoad) {
                tvMsg.setText("提示：全部下载结束");
                File file = new File(tempDir + File.separator + "test.m3u8");
                try {
                    FileOutputStream fos = new FileOutputStream(file);
                    StringBuffer buffer = new StringBuffer(m3U8s.get(0).getStartStr());
                    for (LiteM3U8DownInfo m3U8 : m3U8s) {
                        for (ItemM3U8Ts inf : m3U8.getTsList()) {
                            buffer.append("#EXTINF:");
                            buffer.append(inf.getSeconds());
                            buffer.append(",").append("\r\n");
                            buffer.append(inf.getFileName()).append(".ts").append("\r\n");
                        }
                    }
                    buffer.append("#EXT-X-ENDLIST");
                    fos.write(buffer.toString().getBytes());
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onError(Throwable e) {
            super.onError(e);
//            tvMsg.setText("失败:"+e.toString());
            Log.e("Tag", e.getMessage());
        }


        @Override
        public void onPuase() {
            super.onPuase();
//            tvMsg.setText("提示:暂停");
        }

        @Override
        public void onStop() {
            super.onStop();
        }

        @Override
        public void updateProgress(long readLength, long countLength) {
//            Log.e("Tag","提示:下载中");
//            tvMsg.setText("提示:下载中");
//            progress.setMax((int) countLength);
//            progress.setProgress((int) readLength);


        }
    };
}
